<template>
  <div class="exam-page">
    <!-- 导航栏 -->
    <div class="exam-header">
      <div class="header-left" @click="showConfirmLeave">
        <van-icon name="arrow-left" />
        <span>退出考试</span>
      </div>
      <div class="header-title">{{ examTitle }}</div>
      <div class="header-right">
        <span>{{ answeredCount }}/{{ questionCount }}</span>
      </div>
    </div>

    <!-- 计时器 -->
    <div class="exam-timer" :class="{ warning: timeRemaining <= 300 }">
      剩余时间：{{ formattedTimeRemaining }}
    </div>

    <!-- 考试内容 -->
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" />
    </div>

    <template v-else-if="currentExam && currentQuestion">
      <div class="question-container">
        <!-- 题目信息 -->
        <div class="question-header">
          <div class="question-number">
            第 {{ currentQuestionIndex + 1 }} 题
          </div>
          <div class="question-type">
            {{ getQuestionTypeName(currentQuestion.type) }}
            ({{ currentQuestion.score }}分)
          </div>
        </div>

        <!-- 题目内容 -->
        <div class="question-content">{{ currentQuestion.content }}</div>

        <!-- 选项 -->
        <div class="options-container">
          <template v-if="currentQuestion.type === 'Judgement'">
            <van-radio-group
              :model-value="selectedAnswer"
              @change="onSingleAnswerChange"
            >
              <van-cell-group inset>
                <van-cell
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  clickable
                  @click="selectedAnswer = index"
                >
                  <template #title>
                    <div class="option-item">
                      <div class="option-prefix">{{ option.symbol }}</div>
                      <div class="option-content">{{ option.content }}</div>
                    </div>
                  </template>
                  <template #right-icon>
                    <van-radio :name="index" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </template>

          <template v-else-if="currentQuestion.type === 'Select'">
            <van-radio-group
              :model-value="selectedAnswer"
              @change="onSingleAnswerChange"
            >
              <van-cell-group inset>
                <van-cell
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  clickable
                  @click="selectedAnswer = index"
                >
                  <template #title>
                    <div class="option-item">
                      <div class="option-prefix">{{ option.symbol }}</div>
                      <div class="option-content">{{ option.content }}</div>
                    </div>
                  </template>
                  <template #right-icon>
                    <van-radio :name="index" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-radio-group>
          </template>

          <template v-else-if="currentQuestion.type === 'multiSelect'">
            <van-checkbox-group
              :model-value="selectedAnswers"
              @change="onAnswerChange"
            >
              <van-cell-group inset>
                <van-cell
                  v-for="(option, index) in currentQuestion.options"
                  :key="index"
                  clickable
                  @click="toggleCheckbox(index)"
                >
                  <template #title>
                    <div class="option-item">
                      <div class="option-prefix">{{ option.symbol }}</div>
                      <div class="option-content">{{ option.content }}</div>
                    </div>
                  </template>
                  <template #right-icon>
                    <van-checkbox :name="index" />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </template>
        </div>
      </div>

      <!-- 题目导航 -->
      <div class="question-navigation-wrapper">
        <div class="navigation-header">
          <span>题目导航</span>
          <span>{{ answeredCount }}/{{ questionCount }} 已作答</span>
        </div>
        <div class="question-navigation">
          <div
            v-for="(_, index) in questionCount"
            :key="index"
            class="question-nav-item"
            :class="{
              answered: isQuestionAnswered(index),
              current: currentQuestionIndex === index,
            }"
            @click="goToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>
      </div>
    </template>

    <div v-else class="empty-state">
      <van-empty description="题目加载失败" />
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-action-bar">
      <van-button
        plain
        type="primary"
        size="small"
        @click="prevQuestion"
        :disabled="currentQuestionIndex === 0"
      >
        上一题
      </van-button>
      <van-button type="primary" @click="showAnswerSheet"> 答题卡 </van-button>
      <van-button
        v-if="currentQuestionIndex < questionCount - 1"
        plain
        type="primary"
        size="small"
        @click="nextQuestion"
      >
        下一题
      </van-button>
      <van-button
        v-else
        type="danger"
        size="small"
        @click="confirmSubmit"
        :disabled="loading"
      >
        交卷
      </van-button>
    </div>

    <!-- 答题卡弹出层 -->
    <van-popup
      v-model:show="showAnswerSheetPopup"
      position="bottom"
      round
      :style="{ height: '70%' }"
    >
      <div class="answer-sheet">
        <div class="answer-sheet-header">
          <div class="sheet-title">答题卡</div>
          <div class="sheet-subtitle">
            {{ answeredCount }}/{{ questionCount }} 已作答
          </div>
        </div>

        <div class="answer-sheet-grid">
          <div
            v-for="(_, index) in questionCount"
            :key="index"
            class="answer-sheet-item"
            :class="{
              answered: isQuestionAnswered(index),
              current: currentQuestionIndex === index,
            }"
            @click="goToQuestionAndCloseSheet(index)"
          >
            {{ index + 1 }}
          </div>
        </div>

        <div class="answer-sheet-footer">
          <van-button
            type="primary"
            size="large"
            @click="confirmSubmit"
            :disabled="loading"
          >
            交卷
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";

import { showDialog, showToast } from "vant";
import { useRoute, useRouter } from "vue-router";

import { useExamStore } from "../../stores/exam";

const router = useRouter();
const route = useRoute();
const examStore = useExamStore();

const loading = ref(true);
const showAnswerSheetPopup = ref(false);
const selectedAnswer = ref<number | undefined>(undefined); // 单选答案
const selectedAnswers = ref<number[]>([]); // 多选答案

// 监听当前题目变化
watch(
  () => examStore.currentQuestionIndex,
  () => {
    // 切换题目时，更新选中的答案
    updateSelectedAnswers();
  }
);

// 监听当前题目内容变化
watch(
  () => examStore.currentQuestion,
  () => {
    // 题目内容变化时，更新选中的答案
    updateSelectedAnswers();
  }
);

// 获取考试信息
onMounted(async () => {
  const examId = route.params.id as string;
  if (!examId) {
    showToast("未找到考试ID");
    router.replace("/home");
    return;
  }

  try {
    await examStore.startExam(examId);
    updateSelectedAnswers();
  } catch (error) {
    console.error("开始考试失败", error);
    showToast("开始考试失败");
    router.replace("/home");
  } finally {
    loading.value = false;
  }
});

// 组件销毁时保存答案
onUnmounted(() => {
  saveCurrentAnswer();
  // examStore.saveAnswers(); // 暂时禁用自动保存，避免404错误
});

// 更新当前题目的选中答案
const updateSelectedAnswers = () => {
  if (!examStore.currentExam || !examStore.currentQuestion) {
    console.log("updateSelectedAnswers: 没有当前考试或题目");
    return;
  }

  const examId = examStore.currentExam._id;
  if (!examId) {
    console.log("updateSelectedAnswers: 没有考试ID");
    return;
  }

  const answers = examStore.answers[examId] || [];
  const index = examStore.currentQuestionIndex;
  const currentAnswer = answers[index];
  const currentAnswers = currentAnswer?.selected_answers || [];

  console.log("updateSelectedAnswers:", {
    examId,
    questionIndex: index,
    questionType: examStore.currentQuestion.type,
    currentAnswer,
    currentAnswers,
    allAnswers: answers,
  });

  if (examStore.currentQuestion.type === "multiSelect") {
    selectedAnswers.value = [...currentAnswers]; // 使用展开运算符创建新数组
    selectedAnswer.value = undefined;
  } else {
    selectedAnswers.value = [];
    selectedAnswer.value =
      currentAnswers.length > 0 ? currentAnswers[0] : undefined;
  }

  console.log("updateSelectedAnswers 结果:", {
    selectedAnswer: selectedAnswer.value,
    selectedAnswers: selectedAnswers.value,
  });
};

// 单选答案变更
const onSingleAnswerChange = () => {
  selectedAnswers.value =
    selectedAnswer.value !== undefined ? [selectedAnswer.value] : [];
  saveCurrentAnswer();
};

// 保存当前答案
const saveCurrentAnswer = () => {
  if (!examStore.currentExam || examStore.currentQuestionIndex === undefined)
    return;

  examStore.setAnswer(examStore.currentQuestionIndex, selectedAnswers.value);
};

// 考试标题
const examTitle = computed(() => {
  return examStore.currentExam?.exam_name || "考试进行中";
});

// 题目总数
const questionCount = computed(() => {
  return examStore.questionCount || 0;
});

// 已答题数量
const answeredCount = computed(() => {
  return examStore.answeredCount || 0;
});

// 当前考试
const currentExam = computed(() => {
  return examStore.currentExam || null;
});

// 当前题目
const currentQuestion = computed(() => {
  return examStore.currentQuestion || null;
});

// 当前题目索引
const currentQuestionIndex = computed(() => {
  return examStore.currentQuestionIndex || 0;
});

// 剩余时间
const timeRemaining = computed(() => {
  return examStore.timeRemaining || 0;
});

// 格式化剩余时间
const formattedTimeRemaining = computed(() => {
  return examStore.formattedTimeRemaining || "00:00";
});

// 题目类型名称
const getQuestionTypeName = (type: string) => {
  switch (type) {
    case "Judgement":
      return "判断题";
    case "Select":
      return "单选题";
    case "multiSelect":
      return "多选题";
    default:
      return "未知题型";
  }
};

// 判断题目是否已作答
const isQuestionAnswered = (index: number) => {
  if (!examStore.currentExam) return false;

  const examId = examStore.currentExam._id;
  if (!examId) return false;

  const answers = examStore.answers[examId] || [];

  const answer = answers[index];
  return !!(
    answer &&
    answer.selected_answers &&
    answer.selected_answers.length > 0
  );
};

// 切换多选框
const toggleCheckbox = (index: number) => {
  const position = selectedAnswers.value.indexOf(index);
  if (position === -1) {
    selectedAnswers.value.push(index);
  } else {
    selectedAnswers.value.splice(position, 1);
  }
};

// 答案变更
const onAnswerChange = () => {
  saveCurrentAnswer();
};

// 前往特定题目
const goToQuestion = (index: number) => {
  saveCurrentAnswer();
  examStore.goToQuestion(index);
  // 延迟更新，确保 store 状态已更新
  nextTick(() => {
    updateSelectedAnswers();
  });
};

// 前往特定题目并关闭答题卡
const goToQuestionAndCloseSheet = (index: number) => {
  goToQuestion(index);
  showAnswerSheetPopup.value = false;
};

// 下一题
const nextQuestion = () => {
  saveCurrentAnswer();
  examStore.nextQuestion();
  // 延迟更新，确保 store 状态已更新
  nextTick(() => {
    updateSelectedAnswers();
  });
};

// 上一题
const prevQuestion = () => {
  saveCurrentAnswer();
  examStore.prevQuestion();
  // 延迟更新，确保 store 状态已更新
  nextTick(() => {
    updateSelectedAnswers();
  });
};

// 显示答题卡
const showAnswerSheet = () => {
  saveCurrentAnswer();
  showAnswerSheetPopup.value = true;
};

// 确认提交
const confirmSubmit = async () => {
  try {
    await showDialog({
      title: "确认提交",
      message: "提交后将无法修改答案，确定要提交吗？",
      confirmButtonText: "确认提交",
      cancelButtonText: "继续答题",
    });

    console.log("准备提交考试:", {
      currentRecordId: examStore.currentRecordId,
      currentExam: examStore.currentExam?._id,
      answers: examStore.answers,
    });

    // 保存当前答案
    saveCurrentAnswer();

    // 提交考试
    loading.value = true;
    await examStore.endExam(false);

    // 跳转到结果页
    console.log("考试提交响应数据:", examStore.examResult);

    const recordId =
      examStore.examResult?._id ||
      examStore.examResult?.record_id ||
      examStore.currentRecordId;
    console.log("准备跳转，recordId:", recordId);

    if (recordId) {
      console.log("跳转到结果页:", `/result/${recordId}`);
      router.replace(`/result/${recordId}`);
    } else {
      console.log("没有找到 recordId，跳转到首页");
      router.replace("/home");
    }
  } catch (error) {
    if (error === "cancel") return;
    console.error("提交考试失败", error);
    showToast("提交考试失败");
    loading.value = false;
  }
};

// 显示确认离开对话框
const showConfirmLeave = async () => {
  try {
    await showDialog({
      title: "确认退出",
      message: "退出后答题进度将保存，但计时不会暂停，确定要退出吗？",
      confirmButtonText: "确认退出",
      cancelButtonText: "继续答题",
    });

    saveCurrentAnswer();
    // examStore.saveAnswers(); // 暂时禁用自动保存，避免404错误
    router.replace("/home");
  } catch (error) {
    // 用户取消退出，不做任何操作
  }
};
</script>

<style scoped>
.exam-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 60px;
  position: relative;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #323233;
}

.header-left :deep(.van-icon) {
  margin-right: 4px;
  font-size: 16px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.header-right {
  font-size: 14px;
  color: #969799;
}

.exam-timer {
  background-color: #fff;
  padding: 8px 16px;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  border-bottom: 1px solid #ebedf0;
}

.exam-timer.warning {
  color: #ee0a24;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.8;
  }
  100% {
    opacity: 1;
  }
}

.question-container {
  padding: 16px;
  background-color: #fff;
  margin: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.question-number {
  font-size: 16px;
  font-weight: 500;
}

.question-type {
  font-size: 14px;
  color: #969799;
}

.question-content {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 16px;
  color: #323233;
}

.options-container {
  margin-bottom: 16px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 4px 0;
}

.option-prefix {
  flex-shrink: 0;
  font-weight: 500;
  margin-right: 8px;
  color: #323233;
}

.option-content {
  flex: 1;
}

.question-navigation-wrapper {
  margin: 0 12px 16px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.navigation-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #323233;
}

.question-navigation {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-nav-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background-color: #f2f3f5;
  font-size: 14px;
  color: #323233;
}

.question-nav-item.answered {
  background-color: #1989fa;
  color: #fff;
}

.question-nav-item.current {
  border: 2px solid #1989fa;
  font-weight: 500;
}

.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 16px;
  background-color: #fff;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.answer-sheet {
  padding: 20px 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.answer-sheet-header {
  margin-bottom: 20px;
}

.sheet-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}

.sheet-subtitle {
  font-size: 14px;
  color: #969799;
}

.answer-sheet-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  flex: 1;
  overflow-y: auto;
  padding-bottom: 16px;
}

.answer-sheet-item {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background-color: #f2f3f5;
  font-size: 16px;
  color: #323233;
}

.answer-sheet-item.answered {
  background-color: #1989fa;
  color: #fff;
}

.answer-sheet-item.current {
  border: 2px solid #1989fa;
  font-weight: 500;
}

.answer-sheet-footer {
  margin-top: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
